package me.jollyfly.jshop.web.portal.controller

import me.jollyfly.jshop.user.client.model.dto.LoginUserDTO
import me.jollyfly.jshop.web.portal.service.IndexService
import me.jollyfly.jshop.web.portal.service.LoginAndRegisterService
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Controller
import org.springframework.ui.Model
import org.springframework.validation.BindingResult
import org.springframework.validation.annotation.Validated
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.PathVariable
import org.springframework.web.bind.annotation.PostMapping
import java.util.concurrent.TimeUnit
import javax.servlet.http.Cookie
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse

/**
 *
 *
 * @author jollyfly
 *
 *
 */
@Controller
open class IndexController {

    @Autowired
    private var indexService: IndexService? = null

    @Autowired
    private var loginAndRegisterService: LoginAndRegisterService? = null

    @GetMapping("/")
    fun index(model: Model): String {

        val data = this.indexService!!.loadIndexData()
        model.addAllAttributes(data)


        return "index"
    }

    @GetMapping("/category/list/{id}.html")
    fun toCategoryPage(@PathVariable("id") cId: Long?, model: Model): String {
        return ""
    }

    @GetMapping("index")
    fun index(): String {
        return "index"
    }

    @PostMapping("/login")
    fun login(@Validated loginUserDTO: LoginUserDTO, model: Model, response: HttpServletResponse): String {
        logger.debug("登录用户：username:{}", loginUserDTO.username)
        val loginResult = this.loginAndRegisterService!!.login(loginUserDTO)
        if (loginResult.loginSuccess) {
            logger.info("用户：{}  登录成功", loginUserDTO.username)
            val token = loginResult.token
            val tokenCookie = Cookie("cookie", token)
            tokenCookie.isHttpOnly = true
            tokenCookie.maxAge = 24 * 60 * 60
            response.addCookie(tokenCookie)
            return "redirect:/"
        } else {
            model.addAttribute("errMsg", USERNAME_OR_PASSWORD_ERROR)
        }
        return "login.html"

    }

    companion object {
        private val USERNAME_OR_PASSWORD_ERROR = "用户名或密码错误"
        private val logger: Logger = LoggerFactory.getLogger(IndexController::class.java)
    }


}
